package com.example.myjavaapp.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.myjavaapp.ResourceTable;
import com.example.myjavaapp.domain.SampleItem;
import com.example.myjavaapp.domain.SampleItemProvider;
import com.example.myjavaapp.util.HttpUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class HomeAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_home);
        initview();
    }

    private void initview() {
        TabList tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
        if(tabList!=null){
                tabList.setTabLength(220); // 设置Tab的宽度
                tabList.setTabMargin(30); // 设置两个Tab之间的间距

                TabList.Tab tab = tabList.new Tab(getContext());
                tab.setText("首页");
                tabList.addTab(tab,true);
                tab.setPadding(0, 15, 0, 0);


                TabList.Tab tab2 = tabList.new Tab(getContext());
                tab2.setText("通讯录");
                tabList.addTab(tab2);
                tab2.setPadding(0, 15, 0, 0);

                TabList.Tab tab3 = tabList.new Tab(getContext());
                tab3.setText("网络");
                tabList.addTab(tab3);
                tab3.setPadding(0, 15, 0, 0);

                TabList.Tab tab4 = tabList.new Tab(getContext());
                tab4.setText("存储");
                tabList.addTab(tab4);
                tab4.setPadding(0, 15, 0, 0);

            tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
                @Override
                public void onSelected(TabList.Tab tab) {
                    // 当某个Tab从未选中状态变为选中状态时的回调
                    if(tabList.getSelectedTabIndex()==0){
                        initHome();
                    }else if(tabList.getSelectedTabIndex()==1){
                        initListContainer();
                    }else if(tabList.getSelectedTabIndex()==2){
                        weatherInstall();
                    }else if(tabList.getSelectedTabIndex()==3){
                        initInstall();
                    }
                }
                @Override
                public void onUnselected(TabList.Tab tab) {
                    // 当某个Tab从选中状态变为未选中状态时的回调
                }
                @Override
                public void onReselected(TabList.Tab tab) {
                    // 当某个Tab已处于选中状态，再次被点击时的状态回调
                }
            });
        }
    }

    //首页
    private void initHome() {
        TableLayout tableLayout = (TableLayout) findComponentById(ResourceTable.Id_table1);
        TableLayout tableLayout2 = (TableLayout) findComponentById(ResourceTable.Id_table2);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        DirectionalLayout directionalLayout=(DirectionalLayout) findComponentById(ResourceTable.Id_line1);
        listContainer.setVisibility(Component.HIDE);
        tableLayout2.setVisibility(Component.HIDE);
        directionalLayout.setVisibility(Component.HIDE);
        tableLayout.setVisibility(Component.VISIBLE);
        tableLayout.setHeight(2000);
    }
    //通讯录
    private void initListContainer() {
        TableLayout tableLayout = (TableLayout) findComponentById(ResourceTable.Id_table1);
        TableLayout tableLayout2 = (TableLayout) findComponentById(ResourceTable.Id_table2);
        DirectionalLayout directionalLayout=(DirectionalLayout) findComponentById(ResourceTable.Id_line1);
        tableLayout.setVisibility(Component.HIDE);
        tableLayout2.setVisibility(Component.HIDE);
        directionalLayout.setVisibility(Component.HIDE);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        List<SampleItem> list = getData();
        SampleItemProvider sampleItemProvider = new SampleItemProvider(list, this);
        listContainer.setItemProvider(sampleItemProvider);
        listContainer.setVisibility(Component.VISIBLE);
        listContainer.setMarginTop(0);
        listContainer.setTop(0);
        listContainer.setWidth(1080);
    }
    private ArrayList<SampleItem> getData() {
        ArrayList<SampleItem> list = new ArrayList<>();
        for (int i = 0; i <= 12; i++) {
            list.add(new SampleItem("xunfang" + i + "      15612354856"));
        }
        return list;
    }

    //天气
    private void weatherInstall() {
        TableLayout tableLayout = (TableLayout) findComponentById(ResourceTable.Id_table1);
        TableLayout tableLayout2 = (TableLayout) findComponentById(ResourceTable.Id_table2);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        DirectionalLayout directionalLayout=(DirectionalLayout) findComponentById(ResourceTable.Id_line1);
        tableLayout.setVisibility(Component.HIDE);
        tableLayout2.setVisibility(Component.HIDE);
        listContainer.setVisibility(Component.HIDE);
        directionalLayout.setVisibility(Component.VISIBLE);
        Button btn1 =(Button) findComponentById(ResourceTable.Id_line_button1);
        Button btn2 =(Button) findComponentById(ResourceTable.Id_line_button2);
        Text dateText =(Text)findComponentById(ResourceTable.Id_line_text);
        TaskDispatcher schduleTaskDispatcher = createParallelTaskDispatcher("schdule",TaskPriority.DEFAULT);
        EventRunner eventRunner =EventRunner.getMainEventRunner();
        EventHandler eventHandler = new ClockEventHandler(eventRunner,dateText);
        //directionalLayout.setHeight(2500);
        btn1.setClickedListener(component -> schduleTaskDispatcher.asyncDispatch(() -> {
            HiLog.info(LABEL_LOG,"启动线程，请求网络数据");
            String result = null;
            try {
                result = HttpUtil.httpGet("http://api.k780.com/?app=weather.today&weaid=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json");
            } catch (IOException e) {
                e.getMessage();
            }
            HiLog.info(LABEL_LOG,"结果为："+result);
            JSONObject jsonObj = JSON.parseObject(result);
            String strResult =jsonObj.getString("result");
            HiLog.info(LABEL_LOG,"天气结果为："+strResult);
            int eventId1=0;
            long  param =0;
            InnerEvent event1 =InnerEvent.get(eventId1,param,strResult);
            eventHandler.sendEvent(event1);
        }));
        btn2.setClickedListener(component -> schduleTaskDispatcher.asyncDispatch(() -> {
            String result = null;
            try {
                result = HttpUtil.httpGet("http://api.k780.com/?app=weather.today&weaid=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json");
            } catch (IOException e) {
                e.getMessage();
            }
            JSONObject jsonObj = JSON.parseObject(result);
            String strResult =jsonObj.getString("result");
            savePic(strResult);
        }));
    }

    private void savePic(String result) {
        String fileName="mxyTest.txt";
        String path = "mxy/Test/";
        String strFilePath = path+fileName;
        Context context = getContext();
        File file = new File(strFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(fileName);
            outputStream.write(result.getBytes());
            new ToastDialog(context).setText("文件已生成").show();
            outputStream.close();
        } catch (Exception e) {
            new ToastDialog(context).setText("文件已生成").show();
        }
    }

    //设置
    private void initInstall() {
        TableLayout tableLayout = (TableLayout) findComponentById(ResourceTable.Id_table1);
        tableLayout.setVisibility(Component.HIDE);
        TableLayout tableLayout2 = (TableLayout) findComponentById(ResourceTable.Id_table2);
        tableLayout2.setVisibility(Component.VISIBLE);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        listContainer.setVisibility(Component.HIDE);
        tableLayout2.setHeight(2000);
        tableLayout2.setWidth(1200);
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
